package TeatCase;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.InstrumentationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.Until;
import android.util.ArrayMap;
import android.util.Log;
//import org.openqa.selenium.android.AndroidWebDriver;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.openqa.selenium.android.AndroidWebDriver;

import com.robotium.solo.Solo;

import android.support.test.uiautomator.By;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
//import org.openqa.selenium.android.AndroidDriver;
import QunarTest.QuanrTestCase;

/**
 * Created by zhe.xiao on 2017/7/24.
 */

@RunWith(JUnit4.class)
public class TestT {
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice device = UiDevice.getInstance(instrumentation);
    Solo solo = new Solo(instrumentation);

    @Before
    public void setUp() {
//        try {
//            device.executeShellCommand("am start -n com.Qunar/com.mqunar.splash.SplashActivity");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        com.robotium.solo = new Solo(instrumentation);
    }

    @Test
    public void testT() {

        Log.i("HomeTest", "testStart");
        Log.i("HomeTest", "getCurrentPackageName " + device.getCurrentPackageName());
//        com.robotium.solo.sleep(3000);
//        Log.i("HomeTest", "activity : " + com.robotium.solo.getCurrentActivity().toString());
        Context context = InstrumentationRegistry.getContext();
        Context context1 = InstrumentationRegistry.getTargetContext();
        PackageManager packageManager = context1.getPackageManager();
        Log.i("HomeTest", "getApplicationContext " + context1.getPackageName());
        Log.i("HomeTest", "getApplicationContext " + context.getPackageName());

        Intent launchIntent = new Intent();
        launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        launchIntent.setComponent(new ComponentName("com.Qunar", "com.mqunar.splash.SplashActivity"));
        context1.startActivity(launchIntent);
        Context context2 = InstrumentationRegistry.getContext();
        Context context3 = InstrumentationRegistry.getInstrumentation().getTargetContext();
        Log.i("HomeTest", "getApplicationContext " + context2.getPackageName());
        InstrumentationInfo instrumentationInfo = packageManager.queryInstrumentation("com.Qunar", packageManager.GET_META_DATA).get(0);
        List<ApplicationInfo> appList = packageManager.getInstalledApplications(PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (ApplicationInfo a : appList) {

            Log.i("HomeTest", "getApplicationContext 1" + a.manageSpaceActivityName);
            Log.i("HomeTest", "getApplicationContext 2" + a.processName);
        }
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> appList1 = packageManager.queryIntentActivities(intent, 0);
        Log.i("HomeTest", "getApplicationContext biaozhi" + instrumentationInfo);
        for (ResolveInfo a : appList1) {
            Log.i("HomeTest", "getApplicationContext 3" + a.activityInfo.name);
            Log.i("HomeTest", "getApplicationContext 4" + a.activityInfo.targetActivity);
        }
//        int id = context.getApplicationContext().getResources().getIdentifier("atom_alexhome_push_msg_point", "id", context.getApplicationContext().getPackageName());
        device.wait(Until.findObject(By.res("com.mqunar.atom.alexhome:id/atom_alexhome_push_msg")), 10000).click();
        List<UiObject2> list = device.wait(Until.findObjects(By.res("com.mqunar.atom.im:id/atom_im_name")), 5000);
        Log.i("HomeTest", "size :" + list.size());
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        Log.i("HomeTest", "cn :" + cn.toString());
        for (UiObject2 uiObject2 : list) {
            uiObject2.click();
            ActivityManager am1 = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn1 = am1.getRunningTasks(1).get(0).topActivity;
            Log.i("HomeTest", "cn1 :" + cn1.toString());
            Intent intent1 = new Intent(Intent.ACTION_MAIN, null);
            intent1.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> appList2 = packageManager.queryIntentActivities(intent, 0);
            Log.i("HomeTest", "getApplicationContext biaozhi" + instrumentationInfo);
            for (ResolveInfo a : appList2) {
//                if(a.activityInfo.processName.startsWith("com.mqunar")){
                Log.i("HomeTest", "getApplicationContext 5" + a.activityInfo.name);
                Log.i("HomeTest", "getApplicationContext 6" + a.activityInfo.packageName);
//            }
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ActivityManager am2 = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ComponentName cn2 = am2.getRunningTasks(1).get(0).topActivity;
            Log.i("HomeTest", "cn2 :" + cn2);
            context1.getApplicationContext().getApplicationInfo();

            Log.i("HomeTest", "getLauncherPackageName " + device.getLauncherPackageName());
            Log.i("HomeTest", "getCurrentPackageName " + device.getCurrentPackageName());
            Log.i("HomeTest", "getLastTraversedText " + device.getLastTraversedText());
//            Log.i("HomeTest", "getWebUrl " + solo.getWebUrl());
            break;
        }
        Log.i("HomeTest", "测试webview ");
//        ActivityManager activityManager=(ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
//        Log.i("HomeTest", "runningActivity " + runningActivity);
//        Log.i("HomeTest", "runningActivityClass " + runningActivity.getClass());
        AndroidWebDriver androidWebDriver = new AndroidWebDriver(getCurrentActivity());
        Log.i("HomeTest", "getCurrentUrl " + androidWebDriver.getCurrentUrl());
        androidWebDriver.findElement(org.openqa.selenium.By.name("特惠")).click();


    }

//    private Activity getActivity() {
////        Context context = InstrumentationRegistry.getTargetContext().getApplicationContext();
//        Context context = InstrumentationRegistry.getTargetContext();
//        Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
//        Log.i("HomeTest", "getApplicationContext xz " + instrumentation.getUiAutomation().getRootInActiveWindow().getViewIdResourceName());
//
//        while (!(context instanceof Activity) && context instanceof ContextWrapper) {
//            context = ((ContextWrapper) context).getBaseContext();
//        }
//
//
//        return (Activity) context;
//    }

    public static Activity getCurrentActivity() {
        try {
            Class activityThreadClass = Class.forName("android.app.ActivityThread");
            Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
            Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
            activitiesField.setAccessible(true);
            Map activities = (ArrayMap) activitiesField.get(activityThread);
            Log.i("HomeTest", "activities.size() " + activities.size());
            for (Object activityRecord : activities.values()) {
                Class activityRecordClass = activityRecord.getClass();
                Field pausedField = activityRecordClass.getDeclaredField("paused");
                pausedField.setAccessible(true);
                if (!pausedField.getBoolean(activityRecord)) {
                    Field activityField = activityRecordClass.getDeclaredField("activity");
                    activityField.setAccessible(true);
                    Activity activity = (Activity) activityField.get(activityRecord);
                    Log.i("HomeTest", "activity " + activity);
                    return activity;
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return null;
    }

//    public Activity getActivity(String name){
//        Class<?> c = null;
//        try {
//            c = Class.forName("com.mqunar.atom.browser.QWebBaseActivity");
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//        return c;
//    }
}
